<template>
  <a-modal
    v-model:open="visible"
    title="添加分类"
    width="500px"
    @ok="handleSave"
    @cancel="handleCancel"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical"
    >
      <a-form-item label="分类名称" name="name" required>
        <a-input
          v-model:value="formData.name"
          placeholder="请输入分类名称"
          size="large"
        />
      </a-form-item>
      <a-form-item label="分类描述" name="description">
        <a-textarea
          v-model:value="formData.description"
          placeholder="请输入分类描述"
          :rows="3"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue';
import { message } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';

// 定义props
interface Props {
  visible: boolean;
  primaryCategory: string;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  primaryCategory: 'registration',
});

// 定义emits
const emit = defineEmits<{
  'update:visible': [value: boolean];
  save: [category: any]
}>();

// 响应式数据
const formRef = ref<FormInstance>();

// 表单数据
const formData = reactive({
  name: '',
  description: '',
});

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入分类名称',trigger: 'blur' }],
};

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

// 方法
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    description: '',
  });
};

const handleSave = async () => {
  try {
    await formRef.value?.validate();

    const categoryData = {
      ...formData,
      id: Date.now().toString(),
      primaryCategory: props.primaryCategory,
    };

    emit('save', categoryData);
    message.success('保存成功');
    visible.value = false;
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleCancel = () => {
  visible.value = false;
};

// 监听props变化，初始化表单数据
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible) {
      resetForm();
    }
  },
);
</script>
